// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = _.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const score = event.score || 0
  const coins = event.coins || 0

  try {
    // 获取用户当前数据
    const userResult = await db.collection('users').doc(openid).get()
    const userData = userResult.data

    // 准备更新的数据
    const updateData = {
      updateTime: db.serverDate(),
      coins: userData.coins + coins
    }

    // 如果新分数高于最高分，更新最高分
    if (score > userData.highScore) {
      updateData.highScore = score
    }

    // 更新用户数据
    await db.collection('users').doc(openid).update({
      data: updateData
    })

    // 获取用户排名
    const rankResult = await db.collection('users')
      .aggregate()
      .match({
        highScore: _.gt(0)  // 只统计有分数的用户
      })
      .sort({
        highScore: -1,  // 按分数降序排序
        updateTime: 1   // 同分时按更新时间升序排序
      })
      .group({
        _id: null,
        users: $.push({
          openid: '$openid',
          nickname: '$nickname',
          avatarUrl: '$avatarUrl',
          highScore: '$highScore'
        })
      })
      .end()

    // 计算用户排名
    let myRank = 0
    const rankList = rankResult.list[0]?.users || []
    
    for (let i = 0; i < rankList.length; i++) {
      if (rankList[i].openid === openid) {
        myRank = i + 1
        break
      }
    }

    return {
      success: true,
      data: {
        coins: updateData.coins,
        highScore: updateData.highScore || userData.highScore,
        rank: myRank,
        totalPlayers: rankList.length
      }
    }
  } catch (err) {
    return {
      success: false,
      error: err
    }
  }
}